package com.foodorder.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 简化的WebSocket数据同步处理器
 */
@Component
public class DataSyncWebSocketHandler {
    
    private static final Map<String, Object> sessions = new ConcurrentHashMap<>();
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * 模拟WebSocket连接建立
     */
    public void onConnectionEstablished(String userId, String role) {
        String key = role + "_" + userId;
        sessions.put(key, System.currentTimeMillis());
        System.out.println("WebSocket连接建立：" + key);
    }
    
    /**
     * 模拟WebSocket连接关闭
     */
    public void onConnectionClosed(String userId, String role) {
        String key = role + "_" + userId;
        sessions.remove(key);
        System.out.println("WebSocket连接关闭：" + key);
    }
    
    /**
     * 推送数据更新到指定角色
     */
    public static void pushDataUpdate(String operation, String dataType, Object data, String targetRole) {
        try {
            Map<String, Object> message = Map.of(
                "type", "dataUpdate",
                "operation", operation,
                "dataType", dataType,
                "data", data,
                "timestamp", System.currentTimeMillis()
            );
            
            // 模拟推送到指定角色的所有连接
            long targetConnections = sessions.keySet().stream()
                .filter(key -> key.startsWith(targetRole + "_"))
                .count();
                
            System.out.println("推送数据更新到 " + targetRole + " 角色，连接数: " + targetConnections);
            System.out.println("消息内容: " + objectMapper.writeValueAsString(message));
            
        } catch (Exception e) {
            System.err.println("推送数据更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 推送通知到指定用户
     */
    public static void pushToUser(String userId, String role, Object data) {
        try {
            String key = role + "_" + userId;
            if (sessions.containsKey(key)) {
                Map<String, Object> message = Map.of(
                    "type", "notification",
                    "data", data,
                    "timestamp", System.currentTimeMillis()
                );
                System.out.println("推送通知到用户: " + key);
                System.out.println("通知内容: " + objectMapper.writeValueAsString(message));
            } else {
                System.out.println("用户 " + key + " 未连接");
            }
            
        } catch (Exception e) {
            System.err.println("推送用户通知失败：" + e.getMessage());
        }
    }
    
    /**
     * 广播消息
     */
    public static void broadcast(Object data) {
        try {
            Map<String, Object> message = Map.of(
                "type", "broadcast",
                "data", data,
                "timestamp", System.currentTimeMillis()
            );
            
            System.out.println("广播消息到所有连接，连接数: " + sessions.size());
            System.out.println("广播内容: " + objectMapper.writeValueAsString(message));
            
        } catch (Exception e) {
            System.err.println("广播消息失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取在线连接数
     */
    public static int getOnlineCount() {
        return sessions.size();
    }
    
    /**
     * 获取指定角色的连接数
     */
    public static long getOnlineCountByRole(String role) {
        return sessions.keySet().stream()
            .filter(key -> key.startsWith(role + "_"))
            .count();
    }
} 